package Leetcode;

/**
 * 给你一个字符串 s，找到 s 中最长的回文子串。
 * 输入：s = "babad"
 * 输出："bab"
 * 解释："aba" 同样是符合题意的答案。
 */
public class 力扣5_最长回文子串 {
    public static void main(String[] args) {
        力扣5_最长回文子串 obj = new 力扣5_最长回文子串();
        System.out.println(obj.longestPalindrome("babad"));
        System.out.println(obj.longestPalindrome("cbba"));
    }

    public String longestPalindrome(String s) {
        String result = "";
        char[] bytes = s.toCharArray();
        for (int i = 0; i < bytes.length; i++) {
            String s1 = longStr(s, i, i);
            String s2 = longStr(s, i, i + 1);
            if (s1.length() > result.length()) {
                result = s1;
            }
            if (s2.length() > result.length()) {
                result = s2;
            }
        }
        return result;
    }

    private String longStr(String s, int l, int r) {
        char[] bytes = s.toCharArray();
        int length = s.length();
        while (l >= 0 && r < length && bytes[l] == bytes[r]) {
            l--;
            r++;
        }
        return new String(bytes, l + 1, r - l - 1);
    }
}
